import Vue from 'vue';

// That should be instance of Vue
const ERROR_UNVALID_THAT = -1;
const ERROR_UNVALID_TOKEN = -2;
const ERROR_CODE = {
  ERROR_UNVALID_THAT,
  ERROR_UNVALID_TOKEN,
}

/**
 * 
 * @param {Vue} that instance of Vue
 * @param {Number} id user id
 * @param {Function} success success callback function
 * @param {Function} fail fail callback function
 */
function requestUserInfo(that, id, success, fail) {
  "use strict";
  if (!(that instanceof Vue)) {
    return ERROR_CODE.ERROR_UNVALID_THAT;
  }
  that.axios.get(`${that.GLOBAL.site}/users/${id}`)
    .then(function (res) {
      if (success instanceof Function) {
        success(res);
      }
    })
    .catch(function (error) {
      if (fail instanceof Function) {
        fail(error);
      }
    });
}





/**
 * ADMIN: Check the activity
 * @param {Vue} that instance of Vue
 * @param {Number} id the primary key of administer
 * @param {Number} activityId the primary key of activityId
 * @param {Boolean} state true: aprove, false: deny, null: depreciate
 * @param {Function} success sucess call back function
 * @param {Function} fail fail call back function
 */
function requestCheckActivity(that, id, activityId, state, success, fail) {
  "use strict"
  if (!(that instanceof Vue)) {
    return ERROR_CODE.ERROR_UNVALID_THAT;
  }
  if (!sessionStorage.getItem('token')) {
    return ERROR_CODE.ERROR_UNVALID_TOKEN;
  }
  that.axios.put(`${that.GLOBAL.site}/admins/${id}/check?activityId=${activityId}&state=${state}`, {}, {
      headers: {
        'Authorization': `Bearer:${sessionStorage.getItem('token')}`
      }
    })
    .then(function (res) {
      if (success instanceof Function) {
        success(res);
      }
    })
    .catch(function (error) {
      if (fail instanceof Function) {
        fail(error);
      }
    });
}

/**
 * state : {passing, passed, deny}
 *  
 * @param {Vue} that 
 * @param {number} id
 * @param {String} state
 * @param {Function} success
 * @param {Function} fail 
 */
function requestMessage(that, id, state, success, fail) {
  "use strict";
  if (!(that instanceof Vue)) {
    return ERROR_CODE.ERROR_UNVALID_THAT;
  }
  if (!sessionStorage.getItem("token")) {
    return ERROR_CODE.ERROR_UNVALID_TOKEN;
  }
  that.axios.get(`${that.GLOBAL.site}/users/${id}/message?state=${state}`)
    .then(function (res) {
      if (success instanceof Function) {
        success(res);
      }
    })
    .catch(function (error) {
      if (fail instanceof Function) {
        fail(error);
      }
    });
}

/**
 * Login
 * @param {Vue} that instance of Vue
 * @param {String} account account for login, equivalent to phone number
 * @param {String} password password
 * @param {Function} success success callback fucntion
 * @param {Function} fail fail callback function
 */
function requestLogin(that, account, password, success, fail) {
  "use strict";
  if (!(that instanceof Vue)) {
    return ERROR_CODE.ERROR_UNVALID_THAT;
  }
  that.axios.post(`${that.GLOBAL.site}/login`, {
      account: account,
      password: password,
    })
    .then(function (res) {
      if (success instanceof Function) {
        success(res);
      }
    })
    .catch(function (error) {
      if (fail instanceof Function) {
        fail(error);
      }
    });
}

/**
 * 
 * passed : {true, false}
 * 
 * @param {Vue} that
 * @param {Object} popconfirm
 * @param {number} userId 
 * @param {number} activityId 
 * @param {String} passed 
 */
function requestPassApply(that, popconfirm, userId, activityId, passed) {
  "use strict";
  console.error(userId);
  console.error(activityId);
  if (!(that instanceof Vue)) {
    return ERROR_CODE.ERROR_UNVALID_THAT;
  }
  if (!sessionStorage.getItem("token")) {
    return ERROR_CODE.ERROR_UNVALID_TOKEN;
  }
  that.axios.put(`${that.GLOBAL.site}/users/${userId}/pass/${activityId}?state=${passed}`)
    .then((res) => {
      console.log(res);
      if (res.status == 200) {
        if (res.data.error_code == 0) {
          that.$message.success("成功");
          //设置气泡确认框不弹出
          popconfirm.style.display = "none";
          //设置按钮为灰色
        } else {
          console.error(`error_code: ${res.data.error_code}`);
          console.error(`error_msg: ${res.data.error_msg}`);
          that.$message.error("哎呀，出错了，请稍后再试");
        }
      } else {
        console.error(`res.status: ${res.status}`);
      }
    })
    .catch((err) => {
      console.error(err);
      that.$message.error("哎呀，出错了，请稍后再试");
    });
}

function requestActivityDetail(that, activityId, success, fail) {
  "use strict";
  if (!(that instanceof Vue)) {
    return ERROR_CODE.ERROR_UNVALID_THAT;
  }
  that.axios.get(`${that.GLOBAL.site}/activities/${activityId}`, {}, {
      headers: {
        'Authorization': `Bearer:${sessionStorage.getItem("token")}`
      }
    })
    .then(function (res) {
      if (success instanceof Function) {
        success(res);
      }
    })
    .catch(function (error) {
      if (fail instanceof Function) {
        fail(error);
      }
    });
}

function requestJoinActivity(that, activityId, success, fail) {
  "use strict";
  if (!(that instanceof Vue)) {
    return ERROR_CODE.ERROR_UNVALID_THAT;
  }
  if (!sessionStorage.getItem("token")) {
    return ERROR_CODE.ERROR_UNVALID_TOKEN;
  }
  that.axios.post(`${that.GLOBAL.site}/activities/${activityId}/joiners/${sessionStorage.getItem('id')}`, {}, {
      headers: {
        'Authorization': `Bearer:${sessionStorage.getItem("token")}`
      }
    })
    .then(function (res) {
      if (success instanceof Function) {
        success(res);
      }
    })
    .catch(function (error) {
      if (fail instanceof Function) {
        fail(error);
      }
    });
}

/**
 * 
 * @param {Vue} that 
 * @param {Object} activityInfo 
 * @param {Function} success
 * @param {Function} fail
 */
function requestPublishActivity(that, activityInfo, success, fail) {
  "use strict";
  if (!(that instanceof Vue)) {
    return ERROR_CODE.ERROR_UNVALID_THAT;
  }
  if (!sessionStorage.getItem("token")) {
    return ERROR_CODE.ERROR_UNVALID_TOKEN;
  }
  that.axios.post(`${that.GLOBAL.site}/activities`, {
      activityName: `${activityInfo.name}`,
      activityProfile: `${activityInfo.desc}`,
      activityLocation: `${activityInfo.position}`,
      publisherId: `${sessionStorage.getItem('id')}`,
      activityStart: `${activityInfo.activityStart}`,
      activityEnd: `${activityInfo.activityEnd}`,
    })
    .then(function (res) {
      if (success instanceof Function) {
        const activityId = success(res);
        // 如果fileList非空
        if (that.form.fileList.length > 0) {
          // 转换为formData

          var formData = new FormData();
          that.form.fileList.forEach((fileData) => {
            // 获取源文件对象
            // 这个坑de了好久,只能说antdv的接口文档写的太不清楚了
            formData.append("file", fileData.originFileObj);
          });
          // for (var key of formData.keys()) {
          //   console.log("key:" + key + " value:" + formData.get(key));
          // }
          // 上传图片
          requestPublshPic(that, activityId, formData, (res) => {
              console.log(res);
              if (res.status == 200) {
                if (res.data.error_code == 0) {
                  that.$message.success("图片上传成功");
                } else {
                  console.error(`error_code: ${res.data.error_code}`);
                  console.error(`error_msg: ${res.data.error_msg}`);
                  that.$message.error("哎呀，出错了，请稍后再试");
                  that.uploading = false;
                }
              } else {
                console.error(`res.status: ${res.status}`);
                that.uploading = false;

              }
            },
            (err) => {
              console.error(err);
              that.$message.error("哎呀，出错了，请稍后再试");
              that.uploading = false;
            });

        }

      }
    })
    .catch(function (error) {
      if (fail instanceof Function) {
        fail(error);
      }
    });
}
/**
 * 
 * @param {Vue} that 
 * @param {number} activityId 
 * @param {Object} formData 
 * @param {Function} success 
 * @param {Function} fail 
 */
function requestPublshPic(that, activityId, formData, success, fail) {
  "use strict";
  if (!(that instanceof Vue)) {
    return ERROR_CODE.ERROR_UNVALID_THAT;
  }
  if (!sessionStorage.getItem("token")) {
    return ERROR_CODE.ERROR_UNVALID_TOKEN;
  }

  that.axios.post(`${that.GLOBAL.site}/activities/${activityId}/banner`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },

    })
    .then(function (res) {
      if (success instanceof Function) {
        success(res);
      }
    })
    .catch(function (error) {
      if (fail instanceof Function) {
        fail(error);
      }
    });
}
/**
 * 根据排序类型获取活动
 * @param {Vue} that instance of Vue
 * @param {String} orderType hotest | latest
 * @param {Number} pageIndex page, from 1
 * @param {Number} pageSize page size
 * @param {Function} success success callback function
 * @param {Function} fail fail callback function
 */
function requestActivitiesByOrder(that, orderType, pageIndex, pageSize, success, fail) {
  "use strict";
  if (!(that instanceof Vue)) {
    return ERROR_CODE.ERROR_UNVALID_THAT;
  }
  that.axios
    .get(`${that.GLOBAL.site}/activities/home`, {
      params: {
        order: orderType,
        page: pageIndex,
        size: pageSize,
      },
    })
    .then(function (res) {
      if (success instanceof Function) {
        success(res);
      }
    })
    .catch(function (error) {
      if (fail instanceof Function) {
        fail(error);
      }
    });
}

/**
 * 获取我发布的活动
 * @param {Vue} that instance of Vue
 * @param {Number} id id of user
 * @param {pageIndex} pageIndex the index of page
 * @param {pageSize} pageSize the size of page
 * @param {Function} success sucess callback function
 * @param {Function} fail fail callback function
 */
function requestPublishedActivities(that, id, pageIndex, pageSize, success, fail) {
  "use strict";
  if (!(that instanceof Vue)) {
    return ERROR_CODE.ERROR_UNVALID_THAT;
  }
  that.axios
    .get(`${that.GLOBAL.site}/users/${id}/published`, {
      params: {
        page: pageIndex,
        size: pageSize
      }
    })
    .then(function (res) {
      if (success instanceof Function) {
        success(res);
      }
    })
    .catch(function (error) {
      if (fail instanceof Function) {
        fail(error);
      }
    });
}

/**
 * 获取我参加的活动
 * @param {Vue} that instance of Vue
 * @param {Number} id id of user
 * @param {pageIndex} pageIndex the index of page
 * @param {pageSize} pageSize the size of page
 * @param {Function} success sucess callback function
 * @param {Function} fail fail callback function
 */
function requestJoinedActivities(that, id, pageIndex, pageSize, success, fail) {
  "use strict";
  if (!(that instanceof Vue)) {
    return ERROR_CODE.ERROR_UNVALID_THAT;
  }
  that.axios
    .get(`${that.GLOBAL.site}/users/${id}/joined`,{
      params:{
        page: pageIndex,
        size: pageSize
      }
    })
    .then(function (res) {
      if (success instanceof Function) {
        success(res);
      }
    })
    .catch(function (error) {
      if (fail instanceof Function) {
        fail(error);
      }
    });
}

/**
 * 修改用户信息
 * @param {Vue} that instance of Vue
 * @param {Number} id id of user
 * @param {Object} userInfo edited user information
 * @param {Function} success success callback function
 * @param {Function} fail fail callback function
 */
function requestPutUserInfo(that, id, userInfo, success, fail) {
  "use strict";
  if (!(that instanceof Vue)) {
    return ERROR_CODE.ERROR_UNVALID_THAT;
  }
  that.axios.put(`${that.GLOBAL.site}/users/${id}`, userInfo)
    .then(function (res) {
      if (success instanceof Function) {
        success(res);
      }
    })
    .catch(function (error) {
      if (fail instanceof Function) {
        fail(error);
      }
    });
}

/**
 * Search activities by name
 * @param {Vue} that instance of Vue
 * @param {String} name name of activity
 * @param {Function} success success callback function
 * @param {Function} fail fail callback function
 */
function requestActivitiesByName(that, name, success, fail) {
  'use strict';
  if (!(that instanceof Vue)) {
    return ERROR_CODE.ERROR_UNVALID_THAT;
  }
  that.axios.get(`${that.GLOBAL.site}/activities?name=${name}`)
    .then(function (res) {
      if (success instanceof Function) {
        success(res);
      }
    }).catch(function (error) {
      if (fail instanceof Function) {
        fail(error);
      }
    });
}

export default {
  ERROR_CODE,
  requestUserInfo,
  requestCheckActivity,
  requestLogin,
  requestMessage,
  requestPassApply,
  requestPublishActivity,
  requestPutUserInfo,
  requestJoinedActivities,
  requestPublishedActivities,
  requestActivityDetail,
  requestJoinActivity,
  requestActivitiesByOrder,
  requestActivitiesByName
}